package cn.qvtu.web.controller;

import cn.qvtu.web.domain.Article;
import cn.qvtu.web.domain.Comment;
import cn.qvtu.web.service.IArticleService;
import cn.qvtu.web.service.ICommentService;
import cn.qvtu.web.vo.ArticleVO;
import cn.qvtu.web.vo.LatestArticleVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private IArticleService articleService;

    @Autowired
    private ICommentService commentService;

    /**
     * 后台首页
     */
    @RequestMapping("/")
    public String home(Model model){
        //int articleTotal = articleService.count();
        //int commentTotal = commentService.count();
        PageHelper.startPage(1,5);
        List<LatestArticleVO> latestArticleVOList = articleService.selectLatestArticle();
        PageInfo<LatestArticleVO> articlePage = new PageInfo<LatestArticleVO>(latestArticleVOList);

        PageHelper.startPage(1,5,"created desc");
        List<Comment> commentList = commentService.list();
        PageInfo<Comment> commentPage = new PageInfo<>(commentList);

        model.addAttribute("articlePage",articlePage);
        model.addAttribute("commentPage",commentPage);
        return "admin/index";
    }

    @RequestMapping("/list")
    public String list(Model model,@RequestParam(defaultValue = "1") Integer pageNum){
        PageHelper.startPage(pageNum,10);
        List<ArticleVO> list = articleService.selectArticle();
        PageInfo<ArticleVO> articlePage = new PageInfo<>(list);
        model.addAttribute("articlePage",articlePage);
        return "admin/list";
    }


    @RequestMapping("/edit")
    public String edit(Model model){
        model.addAttribute("article",new Article());
        return "admin/edit";
    }

    @RequestMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, Model model){
        Article  article = articleService.getById(id);
        model.addAttribute("article",article);
        return "admin/edit";
    }


}
